package top.infopub.mgr.fia.service.impl;


import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.fia.dao.OrgBudgetDao;
import top.infopub.mgr.fia.dao.OrgBudgetDetailDao;
import top.infopub.mgr.fia.domain.OrgBudgetDomain;
import top.infopub.mgr.fia.service.OrgBudgetService;
import top.infopub.mgr.fia.vo.OrgBudgetVo;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.model.fia.OrgBudget;
import top.infopub.model.fia.OrgBudgetDetail;
import top.infopub.security.util.SessionUserUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;


@Service
public class OrgBudgetServiceImpl extends GenericServiceImpl<OrgBudget, String> implements OrgBudgetService {

    @Autowired
    private OrgBudgetDao orgBudgetDao;

    @Autowired
    private OrgBudgetDetailDao orgBudgetDetailDao;

    @Autowired
    private WsFlowProcessService wsFlowProcess;

    @Override
    public GenericDao<OrgBudget, String> getDao() {
        return orgBudgetDao;
    }

    @Override
    public Page<OrgBudgetDomain> selectPageByDomainWhere(Page<OrgBudgetDomain> page,
                                                         OrgBudgetVo orgBudgetVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<OrgBudgetDomain>)orgBudgetDao.selectByDomainWhere(orgBudgetVo);
    }

    @Override
    public OrgBudgetVo selectById(String id) {
        return orgBudgetDao.selectById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrgBudget(OrgBudgetVo orgBudget, List<OrgBudgetDetail> orgBudgetDetails) {
        //插入预立项记录
        orgBudgetDao.insertById(orgBudget);

        //批量插入子项
        if (CollectionUtils.isNotEmpty(orgBudgetDetails)) {
            orgBudgetDetailDao.insertByBatch(orgBudgetDetails);
        }

    }

    @Override
    public int count(Integer belongsYear,String hrOrgBillId) {
        return orgBudgetDao.count(belongsYear,hrOrgBillId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void udpOrgBudget(OrgBudgetVo orgBudgetVo) {

        OrgBudget orgBudget = orgBudgetDao.selectByPrimaryKey(orgBudgetVo.getId());
        BeanUtils.copyProperties(orgBudgetVo, orgBudget);
        orgBudget.setProcessStatus("9");//状态改为已生效
        orgBudget.setUptTime(new Date());
        orgBudget.setUptBy(SessionUserUtils.getSessionUserId());
        this.updateBySelective(orgBudget);

        //批量公司费用预算明细
        orgBudgetDetailDao.updateByBatch(orgBudgetVo.getBudgetDetails());

    }

}